package com.xywy.tangandroid.fragment;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.List;

import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.android.volley.VolleyError;
import com.google.gson.reflect.TypeToken;
import com.xywy.tangandroid.R;
import com.xywy.tangandroid.activity.BloodDataListAct;
import com.xywy.tangandroid.activity.BloodRecordAct;
import com.xywy.tangandroid.bean.BloodComputorDesc;
import com.xywy.tangandroid.bean.BloodData;
import com.xywy.tangandroid.bean.User;
import com.xywy.tangandroid.greendao.BaseDao;
import com.xywy.tangandroid.greendao.BloodDataDao;
import com.xywy.tangandroid.util.Constant;
import com.xywy.tangandroid.util.DateUtil;
import com.xywy.tangandroid.util.JsonUtil;
import com.xywy.tangandroid.util.MD5;
import com.xywy.tangandroid.util.NetUtil;
import com.xywy.tangandroid.vollery.GetRequest;
import com.xywy.tangandroid.vollery.OnVolleyResponseListener;
import com.xywy.tangandroid.vollery.VolleyManager;
import com.xywy.tangandroid.widget.MyZxView;

import de.greenrobot.dao.query.QueryBuilder;

/**
 * *****************************************
 * 
 * @Title: BloodFragement.java
 * @Package com.xywy.tangandroid.fragment
 * @Description: TODO(血糖管理)
 * @author smz
 * @date 2014-12-4 上午10:41:18
 * @version V1.0
 ******************************************* 
 */
public class BloodFragement extends Fragment implements OnClickListener {
	private RelativeLayout left_img;
	private TextView middle_title;
	private TextView right_title;
	private LinearLayout tobar;
	private ImageView right_img;
	private RelativeLayout blood_record;
	private TextView day;
	private TextView week;
	private TextView mouth;
	private TextView year;
//	private ImageView test_image;
	private MyZxView zx_view;
	
	BloodDataDao bloodDao;
	
	SharedPreferences bloodSp;
	public static final String pullTime = "pullTime";
	
	private TextView lowest_blood;
	private TextView highest_blood;
	private TextView day_measure;
	private TextView overproof;
	private TextView tv_test_title;
	

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.fragement_blood_manger, null);
		initView(view);
		initListener();
		initdata();
		return view;

	}

	private void initView(View view) {
		left_img = (RelativeLayout) view.findViewById(R.id.left_img);
		middle_title = (TextView) view.findViewById(R.id.middle_title);
		right_title = (TextView) view.findViewById(R.id.right_title);
		right_img = (ImageView) view.findViewById(R.id.right_img);
		left_img.setVisibility(View.INVISIBLE);
		middle_title.setText(getResources().getString(R.string.blood_manger));

		day = (TextView) view.findViewById(R.id.day);
		week = (TextView) view.findViewById(R.id.week);
		mouth = (TextView) view.findViewById(R.id.mouth);
		year = (TextView) view.findViewById(R.id.year);
		
		lowest_blood = (TextView) view.findViewById(R.id.lowest_blood);
		highest_blood = (TextView) view.findViewById(R.id.highest_blood);
		day_measure = (TextView) view.findViewById(R.id.day_measure);
		overproof = (TextView) view.findViewById(R.id.overproof);
		// 到时把此图片 换掉
		zx_view = (MyZxView) view.findViewById(R.id.zx_view);
//		test_image = (ImageView) view.findViewById(R.id.test_image);

		blood_record = (RelativeLayout) view.findViewById(R.id.blood_record);
		tv_test_title = (TextView) view.findViewById(R.id.tv_test_title);
	}

	private void initListener() {
		blood_record.setOnClickListener(this);
		day.setOnClickListener(this);
		week.setOnClickListener(this);
		mouth.setOnClickListener(this);
		year.setOnClickListener(this);

		zx_view.setOnClickListener(this);

	}
    List<BloodData> blood_datas;
	private void initdata() {
		bloodSp = getActivity().getSharedPreferences("tang_config", Context.MODE_PRIVATE);
		initDao();
		getBloodList();
		clickColor(day, R.color.login_buttom_press, R.color.text_color);
	}
	private void initDao(){
		BaseDao basedao = BaseDao.getInstance(getActivity());
		bloodDao = basedao.getBloodDataDao();
	}
	
	@Override
	public void onResume() {
		super.onResume();
		initList();
		switch (current) {
		case 0:
			clickColor(day, R.color.login_buttom_press, R.color.text_color);
			break;
		case 1:
			clickColor(week, R.color.login_buttom_press, R.color.text_color);
			break;
		case 2:
			clickColor(mouth, R.color.login_buttom_press, R.color.text_color);
			break;
		case 3:
			clickColor(year, R.color.login_buttom_press, R.color.text_color);
			break;
		default:
			break;
		}
//		zx_view.setGaveWorth(getDayofData(), MyZxView.MODE_DAY);
	}
	
	private void initList(){
		QueryBuilder<BloodData> qb = bloodDao.queryBuilder();
		blood_datas = qb.list();
		if(blood_datas != null && blood_datas.size()>1)
		Collections.sort(blood_datas, new BloodComputorDesc());
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.day:
			clickColor(day, R.color.login_buttom_press, R.color.text_color);
			break;
		case R.id.week:
			clickColor(week, R.color.login_buttom_press, R.color.text_color);
			break;
		case R.id.mouth:
			clickColor(mouth, R.color.login_buttom_press, R.color.text_color);
			break;
		case R.id.year:
			clickColor(year, R.color.login_buttom_press, R.color.text_color);
			break;
		case R.id.zx_view:

			Intent intent1 = new Intent(getActivity(), BloodDataListAct.class);
			startActivity(intent1);
			break;
		case R.id.blood_record:
			Intent intent = new Intent(getActivity(), BloodRecordAct.class);
			startActivity(intent);
			break;
		default:
			break;
		}
	}

	private int current = 0;
	private void clickColor(View view, int clickColor, int normalclcor) {
		if (view == day) {
			day.setBackgroundResource(clickColor);
			week.setBackgroundResource(normalclcor);
			mouth.setBackgroundResource(normalclcor);
			year.setBackgroundResource(normalclcor);
			zx_view.setGaveWorth(getDayofData(), MyZxView.MODE_DAY);
			current= 0;
		}

		if (view == week) {
			day.setBackgroundResource(normalclcor);
			week.setBackgroundResource(clickColor);
			mouth.setBackgroundResource(normalclcor);
			year.setBackgroundResource(normalclcor);
			zx_view.setGaveWorth(getWeekofData(), MyZxView.MODE_WEEK);
			current =1;
		}

		if (view == mouth) {
			day.setBackgroundResource(normalclcor);
			week.setBackgroundResource(normalclcor);
			mouth.setBackgroundResource(clickColor);
			year.setBackgroundResource(normalclcor);
			zx_view.setGaveWorth(getMounThofData(), MyZxView.MODE_MOUNTH);
			current = 2;
		}
		if (view == year) {
			day.setBackgroundResource(normalclcor);
			week.setBackgroundResource(normalclcor);
			mouth.setBackgroundResource(normalclcor);
			year.setBackgroundResource(clickColor);
			zx_view.setGaveWorth(getYearofData(), MyZxView.MODE_YEAR);
			current = 3;
		}
		setHeader();
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		VolleyManager.cancelRequest(getActivity());
	}
	
	private String sign;
	
	/**
	 * 获取上传的血糖数据列表
	 */
	private void getBloodList() {
		long time = bloodSp.getLong(pullTime, 1l);
		System.out.println("pullTime  "+time);
		try {
			sign = MD5.md5s(Constant.pwd + User.getIUserInstance(getActivity()).getUserid() + "xywy_xuetang");
		} catch (Exception e) {

			e.printStackTrace();
		}
		GetRequest<String> getRequest = new GetRequest<String>(Constant.getBloodListUrl + "&xywy_userid=" + User.getIUserInstance(getActivity()).getUserid() + "" + "&recordtime=" + time
				+ "&app_username=xywy_xuetang" + "&sn=" + sign, String.class, new OnVolleyResponseListener<String>() {

			@Override
			public void onError(VolleyError volleyError) {
			}

			@Override
			public void onSuccess(String response) {
				System.out.println("获取的血糖的数据...." + response);
				try {
					JSONObject object = new JSONObject(response);
					int state = object.optInt("state");
					String mssg = object.optString("error");
					if (state == 200) {
						ParseBloodDataList(object.optString("data"));
					} else {
					}

				} catch (JSONException e) {
					e.printStackTrace();
				}

			}
		});
		getRequest.setIsParseJson(false);
		if (NetUtil.hasNetwork(getActivity())) {
			VolleyManager.addRequest(getRequest, this);
		} else {
		}
	}

	/**
	 * 解析
	 * 
	 * @param optJSONObject
	 */
	protected void ParseBloodDataList(String data) {
		List<BloodData> tempData = (List<BloodData>) JsonUtil.parseJsonToList(data, new TypeToken<List<BloodData>>() {
		}.getType());
		System.out.println("拿到的折现数据---"+tempData.size());
		if(tempData != null && tempData.size()>0){
			bloodSp.edit().putLong(pullTime, Long.parseLong(tempData.get(0).getRecordtime())).commit();
		System.out.println("hahahahahha ");
		try {
			for(BloodData dataItem:tempData){
				int count = 0;
				for(BloodData temp:blood_datas){
					if(temp.getRecordtime().equals(dataItem.getRecordtime())){
						count++;
					}
				}
				if(count == 0){
					System.out.println("原来没有需要插入");
					dataItem.setId(null);
					bloodDao.insert(dataItem);
				}else {
					System.out.println("已经有了");
				}
			}
			initList();
			zx_view.setGaveWorth(getDayofData(), MyZxView.MODE_DAY);
		} catch (Exception e) {
			e.printStackTrace();
		}
		}else {
			bloodSp.edit().putLong(pullTime, System.currentTimeMillis()/1000).commit();
		}
//		zx_view.setGaveWorth(tempData, MyZxView.MODE_DAY);
	}
	private BloodData[] getDayofData(){
		BloodData [] datas = new BloodData[24];
		if(blood_datas != null){
			for(BloodData data:blood_datas){
				long dataTime = Long.parseLong(data.getRecordtime());
				int diff =  DateUtil.getNatureHourDiff(dataTime*1000);
				System.out.println("小时差---"+diff +" 数据 "+data.getCandyvalue());
				if(diff<datas.length)
					datas[diff] = data.clone(); 
			}
		}
		return datas;
	}
	
	private BloodData[] getWeekofData(){
		BloodData [] datas = new BloodData[7];
		for(BloodData data:blood_datas){
			long dataTime = Long.parseLong(data.getRecordtime());
			int diff =  DateUtil.getNatureDayDiff(dataTime*1000);
			System.out.println("天数差值  "+diff);
		    if(diff<datas.length && diff>=0){
		    	datas[diff] = data.clone(); 
		    }
		}
		return datas;
	}
	
	private BloodData[] getMounThofData(){
		BloodData [] datas = new BloodData[30];
		for(BloodData data:blood_datas){
			long dataTime = Long.parseLong(data.getRecordtime());
			int diff =  DateUtil.getNatureDayDiff(dataTime*1000);
			System.out.println("天数差值  "+diff);
		    if(diff<datas.length && diff>=0){
		    	datas[diff] = data.clone(); 
		    }
		}
		return datas;
	}
	
	private BloodData[] getYearofData(){
		BloodData [] datas = new BloodData[12];
		for(BloodData data:blood_datas){
			long dataTime = Long.parseLong(data.getRecordtime());
			int diff =  DateUtil.getNatureMounthDiff(dataTime*1000);
			System.out.println("天数差值  "+diff);
		    if(diff<datas.length){
		    	datas[diff] = data.clone(); 
		    }
		}
		return datas;
	}
	
	private int getExceedStandard(List<BloodData> list ){
		int count = 0 ;
		if(list == null){
			return 0;
		}
		for(BloodData data:list){
			float candyValue = Float.parseFloat(data.getCandyvalue());
			if(candyValue >6){
				count++;
			}
		}
		return count;
	}
	
	private void setHeader(){
		float maxData = 0;
		float minData = 0;
		List<BloodData> temp_list = new ArrayList<BloodData>();
		switch (current) {
		case 0:
			temp_list = getDayList();
			tv_test_title.setText("日测量");
			break;
		case 1:
			temp_list = getWeekList();
			tv_test_title.setText("周测量");
			break;
		case 2:
			temp_list = getMounthList();
			tv_test_title.setText("月测量");
			break;
		case 3:
			tv_test_title.setText("年测量");
			temp_list = getYearList();
			break;
		default:
			break;
		}
		if(temp_list.size()>0){
			maxData = 0;
			minData = Float.parseFloat(temp_list.get(0).getCandyvalue());
			for(BloodData data : temp_list){
				float temp = Float.parseFloat(data.getCandyvalue());
				if(maxData < temp)
					maxData = temp;
				if(minData > temp)
					minData = temp;
			}
		}
		lowest_blood.setText(minData+"");
		highest_blood.setText(maxData+"");
		day_measure.setText(temp_list.size()+"");
		overproof.setText(getExceedStandard(temp_list)+"");
	}
	
	private List<BloodData> getDayList(){
		List<BloodData> list = new ArrayList<BloodData>();
		if (blood_datas != null) {
			for (BloodData data : blood_datas) {
				long dataTime = Long.parseLong(data.getRecordtime());
				int diff = DateUtil.getNatureHourDiff(dataTime*1000);
				if (diff < 24) {
					list.add(data);
				}
			}
		}
		return list;
	}
	
	private List<BloodData> getWeekList(){
		List<BloodData> list = new ArrayList<BloodData>();
		for(BloodData data:blood_datas){
		    long dataTime = Long.parseLong(data.getRecordtime());
			int diff = DateUtil.getNatureDayDiff(dataTime*1000);
		    if(diff<7){
		    	list.add(data);
		       }
		    }
		return list;
	}
	
	private List<BloodData> getMounthList(){
		List<BloodData> list = new ArrayList<BloodData>();
		for(BloodData data:blood_datas){
			 long dataTime = Long.parseLong(data.getRecordtime());
			 int diff = DateUtil.getNatureDayDiff(dataTime*1000);
		    if(diff<31 && diff>=0){
		    	list.add(data);
		    	}
		    }
		return list;
	}
	
	private List<BloodData> getYearList(){
		List<BloodData> list = new ArrayList<BloodData>();
		for(BloodData data:blood_datas){
			 long dataTime = Long.parseLong(data.getRecordtime());
			  int diff = DateUtil.getNatureMounthDiff(dataTime*1000);
		    if(diff<12){
		    	list.add(data);
		    }
		}
		return list;
	}
}
